<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item :label="t('su.invoice.no')" prop="no">
        <el-input
          v-model="queryParams.no"
          :placeholder="t('common.inputText') + t('su.invoice.no')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('su.invoice.invoiceDate')" prop="invoiceDate">
<!--        <el-date-picker-->
<!--          v-model="queryParams.invoiceDate"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          :start-placeholder="t('common.startDate')"-->
<!--          :end-placeholder="t('common.endDate')"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
        <el-date-picker
          v-model="queryParams.startDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="date"
          placeholder="Start Date"
          class="date-picker-item"
        />
        <el-date-picker
          v-model="queryParams.endDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="date"
          placeholder="End Date"
          class="date-picker-item"
        />
      </el-form-item>
<!--      <el-form-item :label="t('su.invoice.dueDate')" prop="dueDate">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.dueDate"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          :start-placeholder="t('common.startDate')"-->
<!--          :end-placeholder="t('common.endDate')"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item :label="t('su.invoice.kind')" prop="kind">
        <el-select
          v-model="queryParams.kind"
          :placeholder="t('common.inputText') + t('su.invoice.kind')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_INVOICE_KIND)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.invoice.customer')" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          :placeholder="t('common.inputText') + t('su.invoice.customer')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.id"
            :label="customer.name"
            :value="customer.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="PI Status" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="Select PI Status"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="status in statusList"
            :key="status.label"
            :label="status.value"
            :value="status.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Production Status" prop="productionStatus">
        <el-select
          v-model="queryParams.productionStatus"
          placeholder="Select Production Status"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="status in productionStatusList"
            :key="status.label"
            :label="status.value"
            :value="status.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Pay Status" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          placeholder="Select Pay Status"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="status in payStatusList"
            :key="status.label"
            :label="status.value"
            :value="status.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.invoice.brand')" prop="brandId">
        <el-select
          v-model="queryParams.brandId"
          :placeholder="t('common.inputText') + t('su.invoice.brand')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.name"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Saler" prop="term">
        <el-input
          v-model="queryParams.term"
          :placeholder="t('common.inputText') + ' Saler'"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
<!--      <el-form-item :label="t('table.createTime')" prop="createTime">-->
<!--        <el-date-picker-->
<!--          v-model="queryParams.createTime"-->
<!--          value-format="YYYY-MM-DD HH:mm:ss"-->
<!--          type="daterange"-->
<!--          :start-placeholder="t('common.startDate')"-->
<!--          :end-placeholder="t('common.endDate')"-->
<!--          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
<!--          class="!w-220px"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('action.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('action.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['su:proforma-invoice:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.create') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['su:proforma-invoice:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @sort-change="handleSortChange">
      <!--      <el-table-column label=" 编号" align="center" prop="id" />-->
      <el-table-column
        label="Invoice"
        align="center"
        prop="no"
        fixed="left"
        width="120px"
        sortable="custom"
      >
        <template #default="scope">
          <router-link :to="'/su/pi/view/' + scope.row.id">
            <span link type="success">{{ scope.row.no }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="PI Status" align="center" prop="status" fixed="left" width="90px" />
      <el-table-column
        :label="t('su.invoice.invoiceDate')"
        align="center"
        prop="invoiceDate"
        sortable="custom"
        :formatter="dateFormatter2"
        fixed="left"
        width="140px"
      />
      <el-table-column
        label="Production"
        align="center"
        prop="productionStatus"
        width="120px"
      />
      <el-table-column label="Pay" align="center" prop="payStatus" width="130px" />

      <el-table-column
        :label="t('su.invoice.customer')"
        align="center"
        prop="customerId"
        width="120px"
      >
        <template #default="scope">
          <router-link :to="'/su/pi/customerPi/' + scope.row.customerId">
            <SelectTag
              pro-key="id"
              pro-name="name"
              :list-value="customerList"
              :value="scope.row.customerId"
            />
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('su.invoice.profit') + '$'"
        align="center"
        prop="totalProfitUs"
        width="120px"
      >
        <template #default="scope">
          {{ priceFmt(scope.row.totalProfitUs) }}
        </template>
      </el-table-column>
      <el-table-column
        label="Sale$"
        align="center"
        width="120px" >
        <template #default="scope">
          {{ priceFmt(scope.row.totalSaleUs) }}
        </template>
      </el-table-column>
      <el-table-column
        label="Purhase$"
        align="center"
        prop="totalPurhaseUs"
        width="120px"
      >
        <template #default="scope">
          {{ priceFmt(scope.row.totalPurhaseUs) }}
        </template>
      </el-table-column>

      <el-table-column
        :label="t('su.invoice.dueDate')"
        align="center"
        prop="dueDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column :label="t('su.invoice.kind')" align="center" prop="kind" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICE_KIND" :value="scope.row.kind" />
        </template>
      </el-table-column>

      <el-table-column :label="t('su.invoice.brand')" align="center" prop="brandId" width="120px">
        <template #default="scope">
          <SelectTag
            pro-key="id"
            pro-name="name"
            :list-value="brandList"
            :value="scope.row.brandId"
          />
        </template>
      </el-table-column>
      <el-table-column :label="t('su.invoice.buyer')" align="center" prop="buyer" />
      <el-table-column :label="t('su.invoice.po')" align="center" prop="po" />
      <el-table-column
        :label="t('su.invoice.payAction')"
        align="center"
        prop="payAction"
        width="120px"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICD_PAY_ACTION" :value="scope.row.payAction" />
        </template>
      </el-table-column>
      <el-table-column :label="t('su.invoice.saler')" align="center" prop="term" />
      <!--        <template #default="scope">-->
      <!--          <dict-tag :type="DICT_TYPE.SU_INVOICE_TERM" :value="scope.row.term" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column :label="t('su.invoice.bill')" align="center" prop="bill" />
<!--      <el-table-column :label="t('su.invoice.remarks')" align="center" prop="remarks" />-->
      <el-table-column :label="t('su.invoice.count')" align="center" prop="count">
        <template #default="scope">
          {{ priceFmt(scope.row.count) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('table.createTime')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column :label="t('su.invoice.no')" align="center" min-width="300px" fixed="right">
        <template #default="scope">
          <router-link :to="'/su/pi/view/' + scope.row.id">
            <el-button link type="success">{{ t('action.preview') }}</el-button>
          </router-link>
          <el-button
            link
            type="primary"
            v-if="'Inquiry' != scope.row.status && 'Delivery' != scope.row.productionStatus"
            @click="delivery(scope.row.id)"
            v-hasPermi="['su:proforma-invoice:update']"
          >
            Delivery
          </el-button>
          <el-button
            link
            type="primary"
            v-if="'Inquiry' != scope.row.status && 'Paied' != scope.row.payStatus"
            @click="pay(scope.row.id)"
            v-hasPermi="['su:proforma-invoice:update']"
          >
            Paied
          </el-button>
          <el-button
            link
            type="primary"
            v-if="'Inquiry' == scope.row.status"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['su:proforma-invoice:update']"
          >
            {{ t('action.edit') }}
          </el-button>
          <el-button
            link
            type="warning"
            v-if="'Inquiry' == scope.row.status"
            @click="handleConfirm(scope.row.id)"
            v-hasPermi="['su:proforma-invoice:confirm']"
          >
            {{ t('common.confirm') }}
          </el-button>
          <el-button
            link
            type="danger"
            v-if="'Inquiry' == scope.row.status"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['su:proforma-invoice:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProformaInvoiceForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProformaInvoiceApi, ProformaInvoiceVO } from '@/api/su/pi'
import ProformaInvoiceForm from './ProformaInvoiceForm.vue'
import { CommonApi } from '@/api/su/common'
import { priceFmt } from '@/utils/ft'

/** 形式发票 列表 */
defineOptions({ name: 'ProformaInvoice' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProformaInvoiceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  startDate: undefined,
  endDate: undefined,
  invoiceDate: [],
  dueDate: [],
  kind: undefined,
  customerId: undefined,
  brandId: undefined,
  status: undefined,
  productionStatus: undefined,
  payStatus: undefined,
  term: undefined,
  createTime: [],
  prop: undefined,
  order: undefined
})

const statusList = ref([
  {
    label: 'Inquiry',
    value: 'Inquiry'
  },
  {
    label: 'Confirm',
    value: 'Confirm'
  }
])
const productionStatusList = ref([
  {
    label: 'Production',
    value: 'Production'
  },
  {
    label: 'Delivery',
    value: 'Delivery'
  }
])
const payStatusList = ref([
  {
    label: 'Arrearage',
    value: 'Arrearage'
  },
  {
    label: 'Paied',
    value: 'Paied'
  }
])
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const brandList = ref([])
const getBrandList = async () => {
  brandList.value = await CommonApi.getBrandList()
}

const customerList = ref([])
const getCompanyList = async () => {
  customerList.value = await CommonApi.getCustomerList()
}

const delivery = async (id: number) => {
  try {
    await message.confirm('Are you sure?')
    await ProformaInvoiceApi.updateProductionStatus(id)
    message.success(t('common.success'))
    await getList()
  } catch {}
}
const pay = async (id: number) => {
  try {
    await message.confirm('Are you sure?')
    await ProformaInvoiceApi.updatePayStatus(id)
    message.success(t('common.success'))
    await getList()
  } catch {}
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProformaInvoiceApi.getProformaInvoicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleSortChange = async(column) => {
  const { prop, order } = column
  queryParams.prop = prop
  queryParams.order = order
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProformaInvoiceApi.deleteProformaInvoice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleConfirm = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('确认该订单后，不可编辑')
    // 发起删除
    await ProformaInvoiceApi.confirmProformaInvoice(id)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProformaInvoiceApi.exportProformaInvoice(queryParams)
    download.excel(data, 'ProformaInvoice' + getNowFormatDate() + '.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

function getNowFormatDate() {
  let date = new Date(),
    year = date.getFullYear(), // 获取完整的年份(4位)
    month = date.getMonth() + 1, // 获取当前月份(0-11,0代表1月)
    strDate = date.getDate() // 获取当前日(1-31)
  if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
  if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
  return `${year}-${month}-${strDate}`
}

/** 初始化 **/
onMounted(() => {
  getBrandList()
  getCompanyList()
  getList()
})
</script>
